<?php

use Drupal\points\Entity\Points;
use Drupal\points\Entity\PointsType;

function points_edit_form($form, &$form_state, $user, PointsType $pointsType) {
  $form_state['user'] = $user;
  $form_state['pointsType'] = $pointsType;

  $form['balance'] = [
    '#title' => t('修改余额 @type (单位:分)', ['@type' => $pointsType->label]),
    '#type' => 'textfield',
    '#required' => TRUE,
    '#element_validate' => ['element_validate_number'],
    '#description' => t('当前:<b>@balance</b>。<br/> 增加填正数，减少填负数',
      ['@balance' => points_get_total($user->uid, $pointsType->type)]),
  ];

  $form['actions'] = ['#type' => 'actions'];
  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => t('保存'),
  ];

  return $form;
}

function points_edit_form_submit($form, &$form_state) {
  $db_transaction = db_transaction();
  try {
    $balance = $form_state['values']['balance'];

    $user = $form_state['user'];
    $pointsType = $form_state['pointsType'];

    if ($pointsType instanceof PointsType) {
      points_to_uid($user->uid, format_string('手动增加:@balance', ['@balance' => $balance]), $pointsType->type, $balance);
    }

    drupal_set_message('修改成功');
  } catch (Exception $e) {
    $db_transaction->rollback();
    watchdog_exception(__FUNCTION__, $e);
    drupal_set_message($e->getMessage(), 'error');
  }
}

function points_entity_form($form, &$form_state, Points $e, $op) {
  $path = drupal_get_path('module', 'points');
  $form_state['build_info']['files']['form'] = $path . '/points.forms.inc';
  $form_state[Points::class] = $e;

  field_attach_form($e->entityType(), $e, $form, $form_state);

  $form['actions'] = ['#type' => 'actions'];
  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => t('保存'),
  ];
  return $form;
}

function points_entity_form_submit($form, &$form_state) {
  $e = $form_state[Points::class];
  if ($e instanceof Points) {
    entity_form_submit_build_entity($e->entityType(), $e, $form, $form_state);
    $e->save();
  }
}
